package com.hsl.housaileibot001.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsl.housaileibot001.common.PageRequest;
import com.hsl.housaileibot001.common.PageResult;
import com.hsl.housaileibot001.mapper.WrongQuestionMapper;
import com.hsl.housaileibot001.model.WrongQuestion;
import com.hsl.housaileibot001.model.vo.WrongQuestionVO;
import com.hsl.housaileibot001.service.WrongQuestionService;
import com.hsl.housaileibot001.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 错题本服务实现类
 */
@Slf4j
@Service
public class WrongQuestionServiceImpl implements WrongQuestionService {

    @Autowired
    private WrongQuestionMapper wrongQuestionMapper;

    @Autowired
    private UserService userService;

    @Override
    public PageResult<WrongQuestionVO> getWrongQuestions(PageRequest pageRequest) {
        // Long userId = getCurrentUserId();
        Long userId = 1988521939104763905L;
        // 构建查询条件
        LambdaQueryWrapper<WrongQuestion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WrongQuestion::getUserId, userId);
        wrapper.eq(WrongQuestion::getDeleted, false);
        wrapper.orderByDesc(WrongQuestion::getLastWrongTime);

        // 分页查询
        Page<WrongQuestion> page = new Page<>(pageRequest.getPageNum(), pageRequest.getPageSize());
        Page<WrongQuestion> result = wrongQuestionMapper.selectPage(page, wrapper);

        // 转换为VO
        List<WrongQuestionVO> voList = result.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        PageResult<WrongQuestionVO> pageResult = new PageResult<>();
        pageResult.setRecords(voList);
        pageResult.setTotal(result.getTotal());
        pageResult.setSize((long) result.getSize());
        pageResult.setCurrent(result.getCurrent());

        return pageResult;
    }

    @Override
    @Transactional
    public void deleteWrongQuestion(Long id) {
        Long userId = getCurrentUserId();

        // 验证错题是否属于当前用户
        WrongQuestion wrongQuestion = wrongQuestionMapper.selectById(id);
        if (wrongQuestion == null || !wrongQuestion.getUserId().equals(userId)) {
            throw new RuntimeException("错题不存在或无权限删除");
        }

        // 逻辑删除
        wrongQuestionMapper.deleteById(id);
        log.info("删除错题成功: userId={}, wrongQuestionId={}", userId, id);
    }

    @Override
    public Map<String, Object> getStats() {
        Long userId = getCurrentUserId();

        // 构建查询条件
        LambdaQueryWrapper<WrongQuestion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WrongQuestion::getUserId, userId);
        wrapper.eq(WrongQuestion::getDeleted, false);

        // 查询总数
        long total = wrongQuestionMapper.selectCount(wrapper);

        Map<String, Object> stats = new HashMap<>();
        stats.put("total", total);

        return stats;
    }

    /**
     * 转换为VO
     */
    private WrongQuestionVO convertToVO(WrongQuestion wrongQuestion) {
        WrongQuestionVO vo = new WrongQuestionVO();
        BeanUtils.copyProperties(wrongQuestion, vo);
        return vo;
    }

    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new RuntimeException("用户未登录");
        }
        com.hsl.housaileibot001.model.vo.UserInfoVO userInfo = userService.getCurrentUser();
        return userInfo.getId();
    }
}

